//
//  Today_VC.m
//  Run
//
//  Created by BetaTheta on 16/3/31.
//  Copyright © 2016年 BetaTheta. All rights reserved.
//

#import "Today_VC.h"

#import "DYDate_CollectionViewCell.h"

#import <CoreMotion/CoreMotion.h>

@interface Today_VC ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) NSString *date;

@property (nonatomic, strong) CMStepCounter *stepCounter;
@property (nonatomic, strong) CMMotionActivityManager *activityManager;
@property (nonatomic, strong) NSOperationQueue *operationQueue;


@property (nonatomic, strong)UICollectionView *dataCollectionView;

@property (nonatomic, strong) NSArray *colorsArr; // 颜色(CGColor)
@property (nonatomic, strong) CAShapeLayer *trackShapeLayer;
@property (nonatomic, strong) CAShapeLayer *progressShapeLayer;

@property (nonatomic, strong) UIView *circleView;


@property (nonatomic, assign) NSInteger stepCounts;
@property (nonatomic, strong) UILabel *stepCountsLabel;

// 天气
@property (nonatomic, strong) UIView *weatherView;

// 动图
@property (nonatomic, strong) UIImageView *runView;


@end

@implementation Today_VC


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];
//    self.stepCounts = 0;
    
    self.navigationItem.title = @"今天";
    
    [self createDateCollectionView];
    
    
    // 计步
    [self createProgressView];
    
    // 天气
    [self createWeatherView];
    
    // 动画图层
    [self createRunImg];

}
#pragma mark - 天气

- (void) createWeatherView {
    self.weatherView = [[UIView alloc] initWithFrame: CGRectMake(0, HEIGHT - WIDTH + 120,  WIDTH,  WIDTH - 210)];
    [self.view addSubview: _weatherView];
    _weatherView.backgroundColor = [UIColor yellowColor];
}

#pragma mark - 晃动触发
-(BOOL)canBecomeFirstResponder {
    return YES;
}
-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
    [self resignFirstResponder];
    [super viewWillDisappear:animated];
}
#pragma mark 运动开始
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    //这里只处理摇晃事件
    if (motion==UIEventSubtypeMotionShake) {
        self.stepCountsLabel.textColor = [UIColor colorWithRed:1.000 green:0.400 blue:0.400 alpha:1.000];
    }
}
#pragma mark 运动结束
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    
    if (motion==UIEventSubtypeMotionShake) {
        self.stepCountsLabel.textColor = [UIColor whiteColor];
    }
    
}


#pragma mark - 计步实现

- (void)stepCountsData{
#if 1
    if (!([CMStepCounter isStepCountingAvailable] || [CMMotionActivityManager isActivityAvailable])) {
        
        NSString *msg = @"您的手机不支持计步, Sorry!";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Opps!!!"
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
    }
    __weak Today_VC *weakSelf = self;
    
    self.operationQueue = [[NSOperationQueue alloc] init];
    
    //更新label
    if ([CMStepCounter isStepCountingAvailable]) {
        
        self.stepCounter = [[CMStepCounter alloc] init];
        
        [self.stepCounter startStepCountingUpdatesToQueue:self.operationQueue
                                                 updateOn:0.1
                                              withHandler:
         ^(NSInteger numberOfSteps, NSDate *timestamp, NSError *error) {
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 
                 if (error) {
                     UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"Opps!" message:@"error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                     [error show];
                 }
                 else {
                     
//                     NSString *text = [NSString stringWithFormat:@" %ld", (long)numberOfSteps];
//                     for (RunData *data in self.coreDataArr) {
//                         data.stepCoutnts = (NSNumber *)numberOfSteps;                     }
//                     [self.coreDataManager saveContext];
                     
//                     weakSelf.stepCountsLabel.text = text;
                     
                 }
             });
         }];
    }

#endif
    
}

#pragma mark - 日历
- (void)createDateCollectionView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.dataCollectionView = [[UICollectionView alloc] initWithFrame: CGRectMake(0, 0, WIDTH, (WIDTH - 60) / 7 ) collectionViewLayout:layout];
    // 边缘弹动
    _dataCollectionView.bounces = NO;
    _dataCollectionView.scrollEnabled = YES;
    // 布局设置
    // 滚动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // cell大小
    layout.itemSize = CGSizeMake((WIDTH - 6 * 20 - 20) / 7 , (WIDTH - 6 * 20 - 20) / 7);

    // 行列间距
    layout.minimumInteritemSpacing = 20;
//    layout.minimumLineSpacing = 0;
   // 边界 上左下右
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    //CollectionView上的背景颜色
    self.dataCollectionView.backgroundColor = [UIColor colorWithWhite:0.902 alpha:1.000];;
    
    _dataCollectionView.delegate = self;
    _dataCollectionView.dataSource = self;
    
    [_dataCollectionView registerClass:[DYDate_CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self.view addSubview:_dataCollectionView];
//    self.navigationItem.titleView = _dataCollectionView;
    
}
- (void)getDeta{
    //得到当前的时间
    NSDate * date = [NSDate date];
    
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd"];
    
    //设置时间间隔（秒）（这个我是计算出来的，不知道有没有简便的方法 )
    NSTimeInterval time = 365 * 24 * 60 * 60;//一年的秒数
    //得到一年之前的当前时间（-：表示向前的时间间隔（即去年），如果没有，则表示向后的时间间隔（即明年））
    
    self.date = [date dateByAddingTimeInterval:-time];
    
    //转化为字符串
//    NSString * startDate = [dateFormatter stringFromDate:lastYear];
    

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 7;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DYDate_CollectionViewCell *dateCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    dateCell.dateLabel.text = @"7";
    return dateCell;
    
}
#pragma mark - 环形渐变色
- (void)createProgressView{
#pragma mark -
    self.trackShapeLayer = [CAShapeLayer layer];
    self.trackShapeLayer.frame = CGRectMake(WIDTH / 2 -  WIDTH * 0.3, WIDTH / 4, WIDTH *0.6 , WIDTH * 0.6 );//设置shapeLayer的尺寸和位置
    //    self.bgShapeLayer.position = self.view.center;
    self.trackShapeLayer.fillColor = [UIColor clearColor].CGColor;//填充颜色为ClearColor
    
    //设置线条的宽度和颜色
    self.trackShapeLayer.lineWidth = 20.0f;
    self.trackShapeLayer.strokeColor = [UIColor whiteColor].CGColor;
    
    // 指定线的边缘是圆的
    self.trackShapeLayer.lineCap = kCALineCapRound;
    //创建出圆形贝塞尔曲线
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, WIDTH *0.6 , WIDTH * 0.6 )];
    //让贝塞尔曲线与CAShapeLayer产生联系
    self.trackShapeLayer.path = circlePath.CGPath;
    
    //添加并显示
    [self.view.layer addSublayer:self.trackShapeLayer];
    
    
#pragma mark -
    //创建出CAShapeLayer
    self.progressShapeLayer = [CAShapeLayer layer];
    self.progressShapeLayer.frame = CGRectMake(0, 0, WIDTH *0.6 , WIDTH * 0.6 );
    
    self.progressShapeLayer.fillColor = [UIColor clearColor].CGColor;//填充颜色为ClearColor
    
    //设置线条的宽度和颜色
    self.progressShapeLayer.lineWidth = 20.0f;

    // 指定线的边缘是圆的
    self.progressShapeLayer.lineCap = kCALineCapRound;
    
    
    //让贝塞尔曲线与CAShapeLayer产生联系
    self.progressShapeLayer.path = circlePath.CGPath;
    
    //添加并显示
    [self.trackShapeLayer addSublayer:self.progressShapeLayer];
    
    //    现在我们要用到CAShapeLayer的两个参数，strokeEnd和strokeStart
    //Stroke:用笔画的意思
    //    在这里就是起始笔和结束笔的位置
    //    Stroke为1的话就是一整圈，0.5就是半圈，0.25就是1/4圈。以此类推
    //
    //    如果我们把起点设为0，终点设为0.75
    
    //设置stroke起始点
    self.progressShapeLayer.strokeStart = 0;
    self.progressShapeLayer.strokeEnd = 0.75;
    
    // 创建颜色数组
    NSMutableArray *colors = [NSMutableArray array];
    for (NSInteger hue = 0; hue <= 360; hue += 5) {
        [colors addObject:(id)[UIColor colorWithHue:0.8*hue/360.0 saturation:1.0 brightness:1.0 alpha:1.0].CGColor];
    }
    self.progressShapeLayer.strokeColor = [UIColor orangeColor].CGColor;
    CALayer *gradientLayer = [CALayer layer];
    CAGradientLayer *gradientLayer1 =  [CAGradientLayer layer];
    gradientLayer1.frame = CGRectMake(- 20, - 20, WIDTH *0.7, WIDTH *0.7);
    [gradientLayer1 setColors:[NSArray arrayWithArray:colors]];
    
    // 设置颜色线条分布的方向
    gradientLayer1.startPoint = CGPointMake(0.0, 0.0);
    gradientLayer1.endPoint = CGPointMake(1.0, 0.0);
    [gradientLayer addSublayer:gradientLayer1];
    [gradientLayer setMask:_progressShapeLayer]; //用progressLayer来截取渐变层
    [self.trackShapeLayer addSublayer:gradientLayer];
#pragma mark -
    self.circleView = [[UIView alloc] initWithFrame:CGRectMake(WIDTH * 0.1, WIDTH * 0.1, WIDTH *0.4 , WIDTH * 0.4)];
    _circleView.layer.cornerRadius = _circleView.bounds.size.width / 2;
    _circleView.backgroundColor = [UIColor whiteColor];
    [self.trackShapeLayer addSublayer:_circleView.layer];
    
    UILabel *bushu = [[UILabel alloc] initWithFrame:CGRectMake(0, WIDTH * 0.35 + 20, 40, 30)];
    bushu.center = CGPointMake(self.view.center.x, bushu.center.y);
    bushu.text = @"步数";
    bushu.textAlignment = NSTextAlignmentCenter;
    bushu.textColor = [UIColor lightGrayColor];
    [self.view addSubview:bushu];
    
    self.stepCountsLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, WIDTH * 0.35, WIDTH * 0.4, WIDTH * 0.4)];
    _stepCountsLabel.center = CGPointMake(self.view.center.x, _stepCountsLabel.center.y);
//    self.stepCountsLabel.text = [NSString stringWithFormat:@"%ld", _stepCounts];
    _stepCountsLabel.text = @"1000";
    _stepCountsLabel.font = [UIFont boldSystemFontOfSize:35];
    
    _stepCountsLabel.textColor = [UIColor blackColor];
    
    _stepCountsLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_stepCountsLabel];
    
    UILabel *mubiao = [[UILabel alloc] initWithFrame:CGRectMake(0, WIDTH * 0.35 + 100, WIDTH * 0.4, 30)];
    mubiao.center = CGPointMake(self.view.center.x, mubiao.center.y);
    mubiao.text = @"目标:10000";
    mubiao.textAlignment = NSTextAlignmentCenter;
    mubiao.textColor = [UIColor lightGrayColor];
    [self.view addSubview:mubiao];
    
    
}
- (void) createRunImg{
    self.runView = [[UIImageView alloc] init];
    _runView.frame = CGRectMake(0, HEIGHT - WIDTH + 150,  WIDTH,  WIDTH - 210);
    [self.view addSubview:_runView];
    // 动图播放
    // 图片数组
    NSMutableArray *imgArr = [NSMutableArray array];
    for (NSInteger i = 1; i < 11; i++) {
        // 获取图片路径
        // 创建图片对象
        // 添加
        NSString *name = [NSString stringWithFormat:@"run%ld", i];
       // 创建图片对象
        UIImage *img = [UIImage imageNamed:name];
        [imgArr addObject:img];
    }
    // 添加到imgView
    // 播放一次所需的时间
    self.runView.animationDuration = 4;
    //动图数组
    self.runView.animationImages = imgArr;
    // 重复次数
    self.runView.animationRepeatCount = NSIntegerMax;
    // 开始动画
    [self.runView startAnimating];
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
